use axum::{extract::{FromRequest, RequestParts}, async_trait, Json};
use crate::utils::rds;

use crate::utils::cookie;
pub struct Auth(pub String) ;




#[async_trait]
impl<B> FromRequest<B> for Auth
where
    B: Send,
{
    type Rejection = Json<serde_json::Value>;
    async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {

        let headers = req.headers().unwrap();
        let user_id = cookie::get_user_id_from_header(headers);
        let auth = user_id.unwrap_or("".to_string());   //这里的auth是redis中的value值，即 session_id
        // println!("auth:{}",&auth);
        if  auth.is_empty() {   //没有cookie时
            // println!("empty");
            return Err(Json(serde_json::json!({
                "status":"Bad",
                "discription":"empty cookie"
            })));	//注意这里返回错误
        }

        let session = rds::get(auth).await; //redis中保存了session内容，如果redis中没有，那也是没有登录
        

        
        match session {
            Ok(session) => Ok(Auth(session)) ,
            Err(_) => Err(Json(serde_json::json!({
                "status":"Bad",
                "discription":"未登录！"
            })))
        }
        // Ok(Auth(auth))
    }
}